package com.HelloWidget;

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import spiaotools.SentParDetector;

public class WikipediaTodaysFeaturedArticle extends ArticleContentDescriptor {

	private Element _root;

	public  void init () throws IOException {
		_doc = Jsoup.connect("http://en.wikipedia.org").get();
		_root = _doc.getElementById("mp-tfa");
		
		
		Element img=_root.getElementsByTag("b").first();
		//System.out.println(img.toString());
		int start=img.toString().indexOf("\"",3);
		int end=img.toString().indexOf("\"",start+1);
		
		_headline = img.attr("title") ;

		_url = "http://en.wikipedia.org" + img.toString().substring(start+1, end);
		//String noHTMLString = _root.toString().replaceAll("\\<.*?\\>", "");
		//noHTMLString = noHTMLString.replaceAll("&nbsp;"," ");

		
		String noHTMLString = _root.text();
		//System.out.println(noHTMLString);
		//String [] splitted = noHTMLString.split("[a-z]\\. [A-Z]");
		//String firstSentence = splitted[0] + splitted[1].charAt(0);
		//System.out.println(firstSentence);
		//System.out.println(oneLine);
		SentParDetector sd = new SentParDetector();
		String sentences = sd.markupRawText(2, noHTMLString);
		
		String oneLine = sentences.split("\\r\\n|\\n")[0];
		_description = oneLine;
		_initialized = true;

	}
	
	@Override
	public CharSequence getHeadline() {		
		return _headline;

	}

	@Override
	public CharSequence getDescription() {
		return _description;
	}

	@Override
	public String getBitmapUrl() {
		Elements imgElements = _root.getElementsByTag("img");
		Element img=imgElements.first();
		String imgUrl=img.toString();
		int fromPlace= imgUrl.indexOf("src=");
		int endPlace=imgUrl.indexOf(" ", fromPlace);
		//System.out.println(imgUrl.substring(fromPlace+5,endPlace-1));
		String result = imgUrl.substring(fromPlace+5,endPlace-1);
		String [] splitted = result.split("/");
		//System.out.println("spl length:"+splitted.length);
		
		String last = "100px"+splitted[splitted.length-1].split("px")[1];
		//System.out.println("wikiPicture last:"+last);
		StringBuffer sb = new StringBuffer("http://");
		int i = 0;
		//for (i=0; i<splitted.length;++i)
			//System.out.println("splitted "+i+":"+splitted[i]);

		for (i=2; i<splitted.length-1;++i) {
			sb.append(splitted[i]+"/");
			//System.out.println("splitted "+i+":"+splitted[i]);
		}
		sb.append(last);
		result = sb.toString();
		//System.out.println("wikiPicture result:"+result);
		return result;
	}

	@Override
	public String getUrl() {
		
		return _url;
	}


	@Override
	public boolean isInitialized() {
		// TODO Auto-generated method stub
		return false;
	}

}
